const db = uniCloud.database();
const { curTimeStamp, timeStamp } = require('../../common/time');
const getIP = require('../../common/ip');
module.exports = async function(options = {}) {
	const { token, uid, clientIP, updateIP = false } = options;
	let where = { token: token };
	let ipaddress = '';
	if (token) {
		where = { token: token };
	} else if (uid) {
		where = { _id: uid };
	}
	if (!token && !uid) {
		throw new Error('获取用户信息缺少token或uid参数！');
	}
	const params = [
		db.collection('uni-id-users').where(where).get()
	]
	if (updateIP) {
		ipaddress = await getIP(clientIP);
		params.push(db.collection('uni-id-users').where(where).update({
			ipaddress
		}))
	}
	const [userRes] = await Promise.all(params);
	if (userRes.data.length) {
		const res = userRes.data[0];
		let { member_time = 0, _id } = res;
		if (member_time == null) {
			member_time = 0;
		}
		// 会员过期了
		if (curTimeStamp() >= member_time && member_time > 0) {
			member_time = -1;
		}
		// member_type 0-非会员 1-普通会员 2-永久会员
		res.member_type = member_time <= 0 ? 0 : res.member_time >= timeStamp(50 * 365) ? 2 : 1;
		res.member_time = member_time;
		res.ipaddress = ipaddress;
		return {
			code: 0,
			data: res,
			msg: '获取成功'
		}
	} else {
		return {
			code: 30000,
			msg: '登录失效'
		}
	}
}